package com.ruoyi.djb.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.AjaxResult.Type;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.djb.domain.DjbDistrict;
import com.ruoyi.djb.domain.DjbReason;
import com.ruoyi.djb.domain.DjbSysConfig;
import com.ruoyi.djb.domain.DjbTrade;
import com.ruoyi.djb.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.ruoyi.djb.config.Constants.SYS_YES;

/**
 * web层通用数据处理
 * 
 * @author ruoyi
 */
public class BaseController
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${djb.env}")
    private String env;

    @Resource
    private DjbSysConfigMapper djbSysConfigMapper;
    @Resource
    private DjbReasonMapper reasonMapper;
    @Resource
    private DjbDistrictMapper districtMapper;
    @Resource
    private DjbTradeMapper tradeMapper;

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder)
    {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport()
        {
            @Override
            public void setAsText(String text)
            {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage()
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 设置请求排序数据
     */
    protected void startOrderBy()
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (StringUtils.isNotEmpty(pageDomain.getOrderBy()))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.orderBy(orderBy);
        }
    }

    /**
     * 获取request
     */
    public HttpServletRequest getRequest()
    {
        return ServletUtils.getRequest();
    }

    /**
     * 获取response
     */
    public HttpServletResponse getResponse()
    {
        return ServletUtils.getResponse();
    }

    /**
     * 获取session
     */
    public HttpSession getSession()
    {
        return getRequest().getSession();
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected TableDataInfo getDataTable(List<?> list){
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 响应返回结果
     * 
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult toAjax(int rows)
    {
        return rows > 0 ? success() : error();
    }

    /**
     * 响应返回结果
     * 
     * @param result 结果
     * @return 操作结果
     */
    protected AjaxResult toAjax(boolean result)
    {
        return result ? success() : error();
    }

    /**
     * 返回成功
     */
    public AjaxResult success()
    {
        return AjaxResult.success();
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error()
    {
        return AjaxResult.error();
    }

    /**
     * 返回成功消息
     */
    public AjaxResult success(String message)
    {
        return AjaxResult.success(message);
    }

    /**
     * 返回成功数据
     */
    public static AjaxResult success(Object data)
    {
        return AjaxResult.success("操作成功", data);
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error(String message)
    {
        return AjaxResult.error(message);
    }

    /**
     * 返回错误码消息
     */
    public AjaxResult error(Type type, String message)
    {
        return new AjaxResult(type, message);
    }

    /**
     * 页面跳转
     */
    public String redirect(String url)
    {
        return StringUtils.format("redirect:{}", url);
    }

    /**
     * 获取用户缓存信息
     */
    public SysUser getSysUser()
    {
        return ShiroUtils.getSysUser();
    }

    /**
     * 设置用户缓存信息
     */
    public void setSysUser(SysUser user)
    {
        ShiroUtils.setSysUser(user);
    }

    /**
     * 获取登录用户id
     */
    public Long getUserId()
    {
        return getSysUser().getUserId();
    }

    /**
     * 获取登录用户名
     */
    public String getLoginName()
    {
        return getSysUser().getLoginName();
    }

    public String checkRequestParameter(Map<String,Object> map){
        for (final Map.Entry<String, Object> ent : map.entrySet()){
            if(ent.getValue()==null){
                return ent.getKey();
            }
        }
        return "";
    }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 方法三：（基于googleMap中的算法得到两经纬度之间的距离,计算精度与谷歌地图的距离精度差不多。）
     *
     * @param longitude1 第一点的经度
     * @param latitude1  第一点的纬度
     * @param longitude2 第二点的经度
     * @param latitude2  第二点的纬度
     * @return 返回的距离，单位m
     */
    public static double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
        double radLat1 = rad(latitude1);
        double radLat2 = rad(latitude2);
        double a = radLat1 - radLat2;
        double b = rad(longitude1) - rad(longitude2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6371000;
        s = Math.round(s * 10000d) / 10000d;
        return s;
    }

    /*获取小程序*/
    public String getAccessToken(){
        DjbSysConfig sysConfig = new DjbSysConfig();
        sysConfig.setSkey("wx.access_token");
        sysConfig.setType("0");
        sysConfig=djbSysConfigMapper.selectDjbSysConfigList(sysConfig).get(0);
        String accessToken = sysConfig.getValue();
        String remark = sysConfig.getRemark();
        Date date = DateUtils.parseDate(remark);
        if(accessToken ==null|| accessToken.isEmpty()||DateUtils.differentBySecond(date,DateUtils.getNowDate())>7000){
//            String s = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token", "grant_type=client_credential&appid=wxc5371f7347ae1227&secret=f74b2e764a8e8b6dcdfb204097cfaff9");
            String s = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token", "grant_type=client_credential&appid=wx023fe513b09669b7&secret=5584582f2847ae22da3d85534ed31541");
            JSONObject ret = JSONObject.parseObject(s);
            if(ret.containsKey("access_token")){
                sysConfig.setValue(accessToken);
                sysConfig.setRemark(DateUtils.getTime());
                djbSysConfigMapper.updateDjbSysConfig(sysConfig);
                accessToken =ret.getString("access_token");
                return accessToken;
            }else{
                String error="getAccessToken失败"+ret.getString("errcode")+ret.getString("errmsg");
                System.out.println(error);
                return null;
            }
        }else{
            return accessToken;
        }
    }

    /*公众号*/
    public String getAccessToken2(){
        DjbSysConfig sysConfig = new DjbSysConfig();
        sysConfig.setSkey("wx.access_token_gzh");
        sysConfig.setType("0");
        sysConfig=djbSysConfigMapper.selectDjbSysConfigList(sysConfig).get(0);
        String accessToken = sysConfig.getValue();
        String remark = sysConfig.getRemark();
        Date date = DateUtils.parseDate(remark);
        if(accessToken ==null|| accessToken.isEmpty()||DateUtils.differentBySecond(date,DateUtils.getNowDate())>7000){
            String s = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token", "grant_type=client_credential&appid=wxc5371f7347ae1227&secret=f74b2e764a8e8b6dcdfb204097cfaff9");
//            String s = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token", "grant_type=client_credential&appid=wx023fe513b09669b7&secret=5584582f2847ae22da3d85534ed31541");
            JSONObject ret = JSONObject.parseObject(s);
            if(ret.containsKey("access_token")){
                accessToken =ret.getString("access_token");
                sysConfig.setValue(accessToken);
                sysConfig.setRemark(DateUtils.getTime());
                djbSysConfigMapper.updateDjbSysConfig(sysConfig);
                return accessToken;
            }else{
                String error="getAccessToken失败"+ret.getString("errcode")+ret.getString("errmsg");
                System.out.println(error);
                return null;
            }
        }else{
            return accessToken;
        }
    }

    /*校验是否手机号*/
    public boolean isPhone(String phone){
        final String regex="[1][3,4,5,6,7,8,9][0-9]{9}$";
        return phone.matches(regex);
    }

    /*发送访客到达提醒通知*/
    public boolean sendVisitArrived(String openId, String visitName, String visitPhone, String visitAddress, String visitReason, String visitType) {
        System.out.println("sendBegin"+openId+":"+visitPhone+":"+visitReason+":"+visitType);
        String token=getAccessToken2();
        if(token==null){
            return false;
        }
        String postUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", openId); // openid
//        jsonObject.put("template_id", "GsEn20xoQCY4O5iFTJvb0gkp_IOZFb6rcF2Yh8S_mDg");
        jsonObject.put("template_id", "iFkpClH9T0t4razRKNll7jojRI_6wMXhlOawSfoUfbM");
        jsonObject.put("lang", "zh_CN");
        JSONObject name = new JSONObject();
        name.put("value", visitName);
        name.put("color", "#173177");
        JSONObject phone = new JSONObject();
        phone.put("value", visitPhone);
        phone.put("color", "#173177");
        JSONObject address = new JSONObject();
        if(visitAddress.length()>20){
            visitAddress=visitAddress.substring(0,16)+"...";
        }
        address.put("value", visitAddress);
        address.put("color", "#C64D4D");

        JSONObject reason = new JSONObject();
        reason.put("value", visitReason);
        reason.put("color", "#173177");
//        JSONObject type = new JSONObject();
//        type.put("value", visitType);
//        type.put("color", "#173177");

        JSONObject data = new JSONObject();
        data.put("thing1",name);
        data.put("phone_number2",phone);
        data.put("thing3",address);
        data.put("const4",reason);
//        data.put("const24",type);
        jsonObject.put("data", data);
        try {
            String string = HttpUtils.httpPostJson(postUrl, jsonObject);
            System.out.println(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /*发送标记通知*/
    public boolean sendTagNotice(String openId,String visitName,String visitPhone,String visitAddress,String visitReason,int id) {
        System.out.println("sendBegin"+openId+":"+visitPhone+":"+visitReason+":");
        String token=getAccessToken2();
        if(token==null){
            return false;
        }
        String postUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", openId);
//        jsonObject.put("template_id", "ppNr5W_Y4RI5KA6lJkx_Tb9y0XKNG4w0KryTePd20XE");
        jsonObject.put("template_id", "ppNr5W_Y4RI5KA6lJkx_TdN9pIN89_e8SuXBrksHXpw");
        jsonObject.put("lang", "zh_CN");
        if(env.equals("PROD")){
            jsonObject.put("url", "https://txeprod.llmmwl.com/djb/user/imageUrl/"+id);
        }else{
            jsonObject.put("url", "https://txetest.llmmwl.com/djb/user/imageUrl/"+id);
        }
//        jsonObject.put("url", "https://localhost/djb/user/imageUrl/"+id);
        JSONObject time = new JSONObject();
        time.put("value", DateUtils.getTime());
        time.put("color", "#173177");
//        JSONObject phone = new JSONObject();
//        phone.put("value", visitPhone);
//        phone.put("color", "#173177");
        JSONObject address = new JSONObject();
        if(visitAddress.length()>20){
            visitAddress=visitAddress.substring(0,16)+"...";
        }
        address.put("value", visitAddress);
        address.put("color", "#C64D4D");

        JSONObject reason = new JSONObject();
        reason.put("value", visitReason);
        reason.put("color", "#173177");
//        JSONObject type = new JSONObject();
//        type.put("value", visitType);
//        type.put("color", "#173177");

        JSONObject data = new JSONObject();
        data.put("time6",time);
//        data.put("phone_number2",phone);
        data.put("thing5",address);
        data.put("const4",reason);
        jsonObject.put("data", data);
        try {
            String string = HttpUtils.httpPostJson(postUrl, jsonObject);
            System.out.println(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /*访客登记审核提醒通知*/
    public boolean sendExamNotice(String openId,String visitName,String visitPhone,String visitAddress,int id,String typeStr,String reasonStr,String userType,int userId) {
        System.out.println("sendExamNotice"+openId+":"+visitPhone+":");
        String token=getAccessToken2();
        if(token==null){
            return false;
        }
        String postUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", openId);
//        jsonObject.put("template_id", "7TfF7KxKFO8pM77ofNnpR3O_N2yhsVrE36Qhc0ISkMw");
        jsonObject.put("template_id", "7TfF7KxKFO8pM77ofNnpRzyuJEaWBpaOWLg-SvKnqls");
        jsonObject.put("lang", "zh_CN");
//        if(env.equals("PROD")){
//            jsonObject.put("url", "https://txeprod.llmmwl.com/djb/user/ExamRegistry/"+id+"/"+userType+"/"+userId);
//        }else{
//            jsonObject.put("url", "https://txetest.llmmwl.com/djb/user/ExamRegistry/"+id+"/"+userType+"/"+userId);
//        }

        if(env.equals("PROD")){
            jsonObject.put("url", "https://txeprod.llmmwl.com/djb/user/toExamRegistry/"+id+"/"+userType+"/"+userId);
        }else{
            jsonObject.put("url", "https://txetest.llmmwl.com/djb/user/toExamRegistry/"+id+"/"+userType+"/"+userId);
        }
        JSONObject name = new JSONObject();
        name.put("value", visitName);
        name.put("color", "#173177");
        JSONObject phone = new JSONObject();
        phone.put("value", visitPhone);
        phone.put("color", "#173177");
        JSONObject address = new JSONObject();
        if(visitAddress.length()>20){
            visitAddress=visitAddress.substring(0,16)+"...";
        }
        address.put("value", visitAddress);
        address.put("color", "#C64D4D");

        JSONObject reason = new JSONObject();
        reason.put("value", reasonStr);
        reason.put("color", "#173177");
        JSONObject type = new JSONObject();
        type.put("value", typeStr);
        type.put("color", "#173177");

        JSONObject data = new JSONObject();
        data.put("thing1",name);
        data.put("phone_number2",phone);
        data.put("thing3",address);
//        data.put("const5",type);
        data.put("const4",reason);
        jsonObject.put("data", data);
        try {
            String string = HttpUtils.httpPostJson(postUrl, jsonObject);
            System.out.println(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /*访客登记审核通过通知*/
    public boolean sendExamPassNotice(String openId,String visitName,String visitPhone,String visitAddress,int id,String typeStr,String reasonStr,String userType,int userId) {
        System.out.println("sendExamNotice"+openId+":"+visitPhone+":");
        String token=getAccessToken2();
        if(token==null){
            return false;
        }
        String postUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", openId);
//        jsonObject.put("template_id", "qfDeSpmDIVkFfyQk-HtbATl3zurJGTjA3IHMV2rtbS8");
        jsonObject.put("template_id", "qfDeSpmDIVkFfyQk-HtbAQlDVAg8o2LIN4i2V16Bh9s");
        jsonObject.put("lang", "zh_CN");
//        if(env.equals("PROD")){
//            jsonObject.put("url", "https://txeprod.llmmwl.com/djb/user/ExamRegistry/"+id+"/"+userType+"/"+userId);
//        }else{
//            jsonObject.put("url", "https://txetest.llmmwl.com/djb/user/ExamRegistry/"+id+"/"+userType+"/"+userId);
//        }
        JSONObject name = new JSONObject();
        name.put("value", visitName);
        name.put("color", "#173177");
        JSONObject phone = new JSONObject();
        phone.put("value", visitPhone);
        phone.put("color", "#173177");
        JSONObject address = new JSONObject();
        if(visitAddress.length()>20){
            visitAddress=visitAddress.substring(0,16)+"...";
        }
        address.put("value", visitAddress);
        address.put("color", "#C64D4D");

        JSONObject reason = new JSONObject();
        reason.put("value", reasonStr);
        reason.put("color", "#173177");
//        JSONObject type = new JSONObject();
//        type.put("value", typeStr);
//        type.put("color", "#173177");

        JSONObject data = new JSONObject();
        data.put("thing1",name);
        data.put("phone_number2",phone);
        data.put("thing3",address);
//        data.put("const5",type);
        data.put("const4",reason);
        jsonObject.put("data", data);
        try {
            String string = HttpUtils.httpPostJson(postUrl, jsonObject);
            System.out.println(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /*身份认证审核提醒*/
    public boolean sendExamNotice2(String openId,String visitName,String mobile,String visitAddress,String userType,int id) {
        System.out.println("sendExamNotice"+openId+":"+userType+":");
        String token=getAccessToken2();
        if(token==null){
            return false;
        }
        String postUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", openId);
//        jsonObject.put("template_id", "30tMk8-x6_7RtbtUxcPUu4-H3Tghz8puWCXdvgR0SMA");
//        jsonObject.put("template_id", "t1lgLYUflniyu1xNx5dW5J8cdJuq1YMFSSb73Z_hJTw");
        jsonObject.put("template_id", "t1lgLYUflniyu1xNx5dW5PtV81ladm83G2pcRFGLfiE");
        jsonObject.put("lang", "zh_CN");
//        if(env.equals("PROD")){
//            jsonObject.put("url", "https://txeprod.llmmwl.com/djb/user/VerifyAddExam/"+id);
//        }else{
//            jsonObject.put("url", "https://txetest.llmmwl.com/djb/user/VerifyAddExam/"+id);
//        }
        if(env.equals("PROD")){
            jsonObject.put("url", "https://txeprod.llmmwl.com/djb/user/toVerifyAddExam/"+id);
        }else{
            jsonObject.put("url", "https://txetest.llmmwl.com/djb/user/toVerifyAddExam/"+id);
        }
        JSONObject name = new JSONObject();
        name.put("value", visitName);
        name.put("color", "#173177");
        JSONObject JSmobile = new JSONObject();
        JSmobile.put("value", mobile);
        JSmobile.put("color", "#173177");
        JSONObject type = new JSONObject();
        type.put("value", userType);
        type.put("color", "#173177");
        JSONObject address = new JSONObject();
        if(visitAddress.length()>20){
            visitAddress=visitAddress.substring(0,16)+"...";
        }
        address.put("value", visitAddress);
        address.put("color", "#C64D4D");

        JSONObject data = new JSONObject();
        data.put("thing1",name);
        data.put("phone_number6",JSmobile);
        data.put("const3",type);
        data.put("thing4",address);
        jsonObject.put("data", data);
        System.out.println(data.toJSONString());
        try {
            String string = HttpUtils.httpPostJson(postUrl, jsonObject);
            System.out.println(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /*身份认证结果通知*/
    public boolean sendExamNotice3(String openId,String visitName,String mobile,String userType,String visitAddress,int id,String resultStr) {
        System.out.println("sendExamNotice"+openId+":"+userType+":");
        String token=getAccessToken2();
        if(token==null){
            return false;
        }
        String postUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", openId);
//        jsonObject.put("template_id", "xAokaaplY4kZkq2fVgsvOxEE2-ekT-4naM9tGrUuwMA");
//        jsonObject.put("template_id", "Gvh2Ptei40eJoO8UxgFUQasuoiVTIRF41x92ghTsmJk");
        jsonObject.put("template_id", "Gvh2Ptei40eJoO8UxgFUQVeZbHMxoe7Ds4KNS5l46CY");
        jsonObject.put("lang", "zh_CN");
        JSONObject name = new JSONObject();
        name.put("value", visitName);
        name.put("color", "#173177");
        JSONObject jsMobile = new JSONObject();
        jsMobile.put("value", mobile);
        jsMobile.put("color", "#173177");
        JSONObject type = new JSONObject();
        type.put("value", userType);
        type.put("color", "#173177");
        JSONObject result = new JSONObject();
        result.put("value", resultStr);
        result.put("color", "#173177");
        JSONObject address = new JSONObject();
        if(visitAddress.length()>20){
            visitAddress=visitAddress.substring(0,16)+"...";
        }
        address.put("value", visitAddress);
        address.put("color", "#C64D4D");

        JSONObject data = new JSONObject();
        data.put("thing9",name);
        data.put("const10",type);
        data.put("thing5",address);
        data.put("const12",result);
        data.put("phone_number11",jsMobile);
        jsonObject.put("data", data);
        try {
            String string = HttpUtils.httpPostJson(postUrl, jsonObject);
            System.out.println(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /*发送小程序登记失效通知*/
    public boolean sendXCXRegExpire(String openId,String visitName,String visitPhone,String visitAddress,String reasonStr) {
        System.out.println("sendXCXRegExpire"+openId+":"+visitName+":"+visitPhone+":"+visitAddress);
        String token=getAccessToken();
        if(token==null){
            return false;
        }
        String postUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", openId); // openid
        jsonObject.put("template_id", "XugivcItiofXVsd1HbaBePDvJdU_zctbkv3TPXDyHv8");
        if(env.equals("PROD")){
            jsonObject.put("miniprogram_state", "formal");
        }else{
            jsonObject.put("miniprogram_state", "trial");
        }
        jsonObject.put("page", "pages/Homepage/Homepage");
        jsonObject.put("lang", "zh_CN");
        JSONObject name = new JSONObject();
        name.put("value", visitName);
        name.put("color", "#173177");
        JSONObject phone = new JSONObject();
        phone.put("value", visitPhone);
        phone.put("color", "#173177");
        JSONObject reason = new JSONObject();
        reason.put("value", reasonStr);
        reason.put("color", "#173177");
//        JSONObject time = new JSONObject();
//        time.put("value", tuangoutime);
//        time.put("color", "#173177");
        JSONObject address = new JSONObject();
        if(visitAddress.length()>20){
            visitAddress=visitAddress.substring(0,16)+"...";
        }
        address.put("value", visitAddress);
        address.put("color", "#C64D4D");
        JSONObject data = new JSONObject();
        data.put("thing1",name);
        data.put("phone_number2",phone);
        data.put("thing3",address);
        data.put("thing4",reason);
        jsonObject.put("data", data);
        try {
            String string = HttpUtils.httpPostJson(postUrl, jsonObject);
            System.out.println(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /*发送公众号登记失效通知*/
    public boolean sendGZHRegExpire(String openId2,String visitName,String visitPhone,String visitAddress,String reasonStr) {
        System.out.println("sendXCXRegExpire"+openId2+":"+visitName+":"+visitPhone+":"+visitAddress);
        String token=getAccessToken2();
        if(token==null){
            return false;
        }
        String postUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/bizsend?access_token=" + token;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", openId2); // openid
        jsonObject.put("template_id", "thvqUEX2nVhx9MLhGAuUf3q4w9X6HX1QSVut2B43KTQ");
        JSONObject name = new JSONObject();
        name.put("value", visitName);
        JSONObject phone = new JSONObject();
        phone.put("value", visitPhone);
        JSONObject reason = new JSONObject();
        reason.put("value", reasonStr);
//        JSONObject time = new JSONObject();
//        time.put("value", tuangoutime);
//        time.put("color", "#173177");
        JSONObject address = new JSONObject();
        if(visitAddress.length()>20){
            visitAddress=visitAddress.substring(0,16)+"...";
        }
        address.put("value", visitAddress);
        JSONObject data = new JSONObject();
        data.put("thing1",name);
        data.put("phone_number2",phone);
        data.put("thing3",address);
        data.put("thing4",reason);
        jsonObject.put("data", data);
        try {
            String string = HttpUtils.httpPostJson(postUrl, jsonObject);
            System.out.println(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    void initDjbReason(Integer districtId,int type){
        if(type==1){
            DjbReason djbReason2 = new DjbReason();
            djbReason2.setDistrictId(districtId);
            djbReason2.setReason("维保");
            djbReason2.setType(0);
            djbReason2.setIsOpen(1);
            reasonMapper.insertDjbReason(djbReason2);
            DjbReason djbReason6 = new DjbReason();
            djbReason6.setDistrictId(districtId);
            djbReason6.setReason("拜访亲友");
            djbReason6.setType(0);
            djbReason6.setIsOpen(1);
            reasonMapper.insertDjbReason(djbReason6);
            DjbReason djbReason1 = new DjbReason();
            djbReason1.setDistrictId(districtId);
            djbReason1.setReason("送货");
            djbReason1.setType(0);
            djbReason1.setIsOpen(1);
            reasonMapper.insertDjbReason(djbReason1);
            DjbReason djbReason8 = new DjbReason();
            djbReason8.setDistrictId(districtId);
            djbReason8.setReason("接人送人");
            djbReason8.setType(0);
            djbReason8.setIsOpen(1);
            reasonMapper.insertDjbReason(djbReason8);
            DjbReason djbReason3 = new DjbReason();
            djbReason3.setDistrictId(districtId);
            djbReason3.setReason("装修");
            djbReason3.setType(0);
            djbReason3.setIsOpen(1);
            reasonMapper.insertDjbReason(djbReason3);
            DjbReason djbReason7 = new DjbReason();
            djbReason7.setDistrictId(districtId);
            djbReason7.setReason("住户换车");
            djbReason7.setType(0);
            djbReason7.setIsOpen(1);
            reasonMapper.insertDjbReason(djbReason7);
            DjbReason djbReason4 = new DjbReason();
            djbReason4.setDistrictId(districtId);
            djbReason4.setReason("搬家");
            djbReason4.setType(0);
            djbReason4.setIsOpen(1);
            reasonMapper.insertDjbReason(djbReason4);
            DjbReason djbReason10 = new DjbReason();
            djbReason10.setDistrictId(districtId);
            djbReason10.setReason("其他事由");
            djbReason10.setType(0);
            djbReason10.setIsOpen(1);
            reasonMapper.insertDjbReason(djbReason10);
//
//            DjbReason djbReason5 = new DjbReason();
//            djbReason5.setDistrictId(districtId);
//            djbReason5.setReason("外卖");
//            djbReason5.setType(0);
//            djbReason5.setIsOpen(1);
//            reasonMapper.insertDjbReason(djbReason5);
        }else if(type==2||type==3){
            DjbReason djbReason1 = new DjbReason();
            djbReason1.setDistrictId(districtId);
            djbReason1.setReason("业务");
            djbReason1.setType(0);
            djbReason1.setIsOpen(1);
            reasonMapper.insertDjbReason(djbReason1);
            DjbReason djbReason2 = new DjbReason();
            djbReason2.setDistrictId(districtId);
            djbReason2.setReason("维保");
            djbReason2.setType(0);
            djbReason2.setIsOpen(1);
            reasonMapper.insertDjbReason(djbReason2);
            DjbReason djbReason3 = new DjbReason();
            djbReason3.setDistrictId(districtId);
            djbReason3.setReason("送货");
            djbReason3.setType(0);
            djbReason3.setIsOpen(1);
            reasonMapper.insertDjbReason(djbReason3);
            DjbReason djbReason4 = new DjbReason();
            djbReason4.setDistrictId(districtId);
            djbReason4.setReason("面试");
            djbReason4.setType(0);
            djbReason4.setIsOpen(1);
            reasonMapper.insertDjbReason(djbReason4);
            DjbReason djbReason5 = new DjbReason();
            djbReason5.setDistrictId(districtId);
            djbReason5.setReason("外卖");
            djbReason5.setType(0);
            djbReason5.setIsOpen(1);
            reasonMapper.insertDjbReason(djbReason5);
            DjbReason djbReason6 = new DjbReason();
            djbReason6.setDistrictId(districtId);
            djbReason6.setReason("临时换车");
            djbReason6.setType(0);
            djbReason6.setIsOpen(1);
            reasonMapper.insertDjbReason(djbReason6);
            DjbReason djbReason7 = new DjbReason();
            djbReason7.setDistrictId(districtId);
            djbReason7.setReason("接人送人");
            djbReason7.setType(0);
            djbReason7.setIsOpen(1);
            reasonMapper.insertDjbReason(djbReason7);
            DjbReason djbReason10 = new DjbReason();
            djbReason10.setDistrictId(districtId);
            djbReason10.setReason("其他事由");
            djbReason10.setType(0);
            djbReason10.setIsOpen(1);
            reasonMapper.insertDjbReason(djbReason10);
        }
    }

    /*小程序订阅消息-身份认证结果*/
    public boolean sendUserVerifyResult(String openId,String name,String mobile,String address,String userType) {
        String token=getAccessToken();
        if(token==null){
            return false;
        }
        String postUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", openId); // openid
        jsonObject.put("template_id", "o3noe43YtYEiSZmiSY1LL1xoD_V5KK4HY2hAkZ_Oeww");
        if(env.equals("PROD")){
            jsonObject.put("miniprogram_state", "formal");
        }else{
            jsonObject.put("miniprogram_state", "trial");
        }
        jsonObject.put("page", "pages/SelectMyCells/SelectMyCells");
        jsonObject.put("lang", "zh_CN");
        JSONObject jsName = new JSONObject();
        jsName.put("value", name);
        jsName.put("color", "#173177");
        JSONObject jsMobile = new JSONObject();
        jsMobile.put("value", mobile);
        jsMobile.put("color", "#173177");
        JSONObject jsAddress = new JSONObject();
        if(address.length()>20){
            address=address.substring(0,16)+"...";
        }
        jsAddress.put("value", address);
        jsAddress.put("color", "#173177");
        JSONObject jsUserType = new JSONObject();
        jsUserType.put("value", userType);
        jsUserType.put("color", "#C64D4D");
        JSONObject data = new JSONObject();
        data.put("thing1",jsName);
        data.put("phone_number2",jsMobile);
        data.put("thing3",jsAddress);
        data.put("thing4",jsUserType);
        jsonObject.put("data", data);
        try {
            String string = HttpUtils.httpPostJson(postUrl, jsonObject);
            System.out.println(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /*小程序订阅消息-访客登记通过提醒*/
    public boolean sendUserExamPass(String openId,String name,String mobile,String address,String reason) {
        String token=getAccessToken();
        if(token==null){
            return false;
        }
        String postUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", openId); // openid
        jsonObject.put("template_id", "DBtXnsyiw9G45EzSPZiOFMnLd5huVl7oZWkzAMydA8c");
        if(env.equals("PROD")){
            jsonObject.put("miniprogram_state", "formal");
        }else{
            jsonObject.put("miniprogram_state", "trial");
        }
//        jsonObject.put("page", "pages/SelectMyCells/SelectMyCells");
        jsonObject.put("lang", "zh_CN");
        JSONObject jsName = new JSONObject();
        jsName.put("value", name);
        jsName.put("color", "#173177");
        JSONObject jsMobile = new JSONObject();
        jsMobile.put("value", mobile);
        jsMobile.put("color", "#173177");
        JSONObject jsAddress = new JSONObject();
        if(address.length()>20){
            address=address.substring(0,16)+"...";
        }
        jsAddress.put("value", address);
        jsAddress.put("color", "#173177");
        JSONObject jsReason = new JSONObject();
        jsReason.put("value", reason);
        jsReason.put("color", "#C64D4D");
        JSONObject data = new JSONObject();
        data.put("thing1",jsName);
        data.put("phone_number2",jsMobile);
        data.put("thing3",jsAddress);
        data.put("thing4",jsReason);
        jsonObject.put("data", data);
        try {
            String string = HttpUtils.httpPostJson(postUrl, jsonObject);
            System.out.println(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /*校验手机验证码*/
    public  boolean checkPhoneCode(String phone,int code){
        if(env.equals("TEST")){
            return true;
        }

//        DxjlPhoneCode phoneCode1 = phoneCodeMapper.selectDxjlPhoneCodeByPhone(phone);
//        if(phoneCode1==null || !phoneCode1.getCode().equals(String.valueOf(code)) || DateUtils.differentMillissByMillisecond(phoneCode1.getCreateTime(),DateUtils.getNowDate())>600){
//            return false;
//        }
//        phoneCode1.setStatus(0);
//        phoneCodeMapper.updateDxjlPhoneCode(phoneCode1);
        return true;
    }

//    public AlipayClient getAliPayClient(){
//        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
//                chargeConfig.getAliAppid(),
//                chargeConfig.getAliPrivatekey(),
//                "json",
//                "UTF-8",
//                chargeConfig.getAliPublickey(),
//                "RSA2");
//        return alipayClient;
//    }

    /*发送入场短信*/
    public void sendIncomeSMS(String phone,String car,String address,String templateId,DjbDistrict district){
        DefaultProfile profile = DefaultProfile.getProfile("cn-qingdao", "LTAIw5DUpj6wdXJ2", "dJQG5ShMic015K9lVdEbhvSOM7wfbr");
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request;
        request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "小门官");
        request.putQueryParameter("TemplateCode", templateId);
        JSONObject jo=new JSONObject();
        jo.put("code",car);
        jo.put("address",address);
        request.putQueryParameter("TemplateParam", jo.toString());
        try {
            CommonResponse response2 = client.getCommonResponse(request);
            jo=JSONObject.parseObject(response2.getData());
            if(jo.getString("Code").equals("OK")){
                System.out.println("发送入场短信成功");
            }else{
                logger.error("发送入场短信失败"+jo.toJSONString());
            }
        } catch (ClientException e) {
            e.printStackTrace();
            logger.error("发送短信错误:"+e.getMessage());
            logger.error("发送入场短信失败"+e.getMessage());
        }
        /*扣费*/
        district.setBalance(district.getBalance()-10);
        districtMapper.updateDjbDistrict(district);
        DjbTrade djbTrade = new DjbTrade();
        djbTrade.setChargeId(null);
        djbTrade.setDistrictId(district.getId());
        djbTrade.setUserId(null);
        djbTrade.setMoney(10);
        djbTrade.setCreateTime(DateUtils.getNowDate());
        djbTrade.setTradeTime(DateUtils.getNowDate());
        djbTrade.setPayType("");
        djbTrade.setStatus(SYS_YES);
        djbTrade.setName("进场短信提醒服务");
        djbTrade.setDirect("出");
        djbTrade.setTradeType("消费");
        djbTrade.setBalance(district.getBalance());
        tradeMapper.insertDjbTrade(djbTrade);
    }

    /*身份信息一致性校验*/
    public boolean checkNameAndIdNumber(String name,String idNumber,DjbDistrict district) {
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(HttpUtils.httpPostString("https://api.253.com/open/idcard/id-card-auth","appId=BHvTVz91&appKey=nyyZVwlc&name="+name+"&idNum="+idNumber));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        // 2.处理返回结果
        String code = jsonObject.getString("code");
        if ("200000".equals(code) && jsonObject.get("data") != null) {
            String result = jsonObject.getJSONObject("data").getString("result");
            /*扣费*/
            district.setBalance(district.getBalance()-10);
            districtMapper.updateDjbDistrict(district);
            DjbTrade djbTrade = new DjbTrade();
            djbTrade.setChargeId(null);
            djbTrade.setDistrictId(district.getId());
            djbTrade.setUserId(null);
            djbTrade.setMoney(10);
            djbTrade.setCreateTime(DateUtils.getNowDate());
            djbTrade.setTradeTime(DateUtils.getNowDate());
            djbTrade.setPayType("");
            djbTrade.setStatus(SYS_YES);
            djbTrade.setName("身份信息一致性校验服务");
            djbTrade.setDirect("出");
            djbTrade.setTradeType("消费");
            djbTrade.setBalance(district.getBalance());
            tradeMapper.insertDjbTrade(djbTrade);
            return result.equals("01");
        }else{
            return false;
        }
    }


}